package com.zyp.jobseeker.config;

import com.zyp.jobseeker.typehandler.*;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * MyBatis配置类
 */
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.zyp.jobseeker.mapper")
public class MyBatisConfig {

    /**
     * 配置SqlSessionFactory
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        // 配置MyBatis XML映射文件位置
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] mapperLocations = resolver.getResources("classpath:mapper/*.xml");
        sqlSessionFactoryBean.setMapperLocations(mapperLocations);        // 注册多个枚举类型处理器（推荐方式）
        sqlSessionFactoryBean.setTypeHandlers(
                new UserRoleTypeHandler(),
                new UserStatusTypeHandler(),
                new PositionStatusTypeHandler(),
                new ApplicationStatusTypeHandler(),
                new InterviewStatusTypeHandler()
        );
        // 配置类型别名包
        sqlSessionFactoryBean.setTypeAliasesPackage("com.zyp.jobseeker.entity");

        // 显式配置MyBatis配置
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);

        return sqlSessionFactoryBean;
    }

    /**
     * 配置事务管理器
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

}